/**
 * 操控数据的公共函数方法
 * batchDelete 批量删除复合条件的数据 返回删除数组  会改变原始数组。
 * valueToLabel 后台返回的value值转对应的label
 * isEqual 比较两个对象的值是否相等
 */

import { flattenTreeData } from './treeDataHandle'

/**
 * 批量删除复合条件的数据 返回删除数组  会改变原始数组。
 * @param arr 传入的数组
 */
const batchDelete = <T>(arr: T[], callBack: (item: T, index?: number) => boolean): T[] => {
  const deleteArr: T[] = []
  for (let index = arr.length - 1; index >= 0; index--) {
    if (callBack(arr[index], index)) {
      deleteArr.push(...arr.splice(index, 1))
    }
  }
  return deleteArr
}

type Options = [
  {
    label: string
    value: string | number
    children?: Options
  }
]
/**
 * 后台返回的value值转对应的label
 * @param _value
 * @param _options 查询字典
 * @param separator 字符串转数组的分割符号
 */
const valueToLabel = (
  _value: Array<string | number> | string,
  _options: Options,
  separator: string
) => {
  if (_value === undefined) {
    return undefined
  }
  let valueArr: Array<string | number> = []
  const resultArr: string[] = []
  if (!Array.isArray(_value)) {
    valueArr = _value.split(separator).filter(item => item)
  } else {
    valueArr = _value
  }
  const options = flattenTreeData(_options)
  options.forEach(item => {
    if (valueArr.includes(item.value)) {
      resultArr.push(item.label)
      valueArr = valueArr.filter(value => value !== item.value)
    }
  })

  if (valueArr.length > 0) {
    return `数据解析失败`
  } else {
    return resultArr.join()
  }
}

/**
 * 比较两个对象是否相等
 * @param obj1
 * @param obj2
 * @returns
 */
function isEqual(obj1: any, obj2: any): boolean {
  if (obj1 === obj2) {
    return true
  }

  if (typeof obj1 !== typeof obj2 || obj1 === null || obj2 === null) {
    return false
  }

  if (typeof obj1 !== `object` || typeof obj2 !== `object`) {
    return obj1 === obj2
  }

  if (obj1 instanceof Date && obj2 instanceof Date) {
    return obj1.getTime() === obj2.getTime()
  }

  if (Array.isArray(obj1) !== Array.isArray(obj2)) {
    return false
  }

  const keys1 = Object.keys(obj1)
  const keys2 = Object.keys(obj2)

  if (keys1.length !== keys2.length) {
    return false
  }

  keys1.sort()
  keys2.sort()

  for (let i = 0; i < keys1.length; i++) {
    const key1 = keys1[i]
    const key2 = keys2[i]

    if (key1 !== key2) {
      return false
    }

    if (!isEqual(obj1[key1], obj2[key2])) {
      return false
    }
  }

  return true
}

export { batchDelete, valueToLabel, isEqual }
